﻿using CommunityToolkit.Maui.Alerts;
using Compass.Maui.Services.FinishGoods;

namespace Compass.Maui.ViewModels.FinishGoods;

[QueryProperty(nameof(Result), nameof(Result))]
[QueryProperty(nameof(PackingListDto), nameof(PackingListDto))]
public partial class ShippingPalletPageViewModel : BaseViewModel
{
    private readonly IPalletService _palletService;
    public ShippingPalletPageViewModel(IPalletService palletService)
    {
        _palletService = palletService;
    }
    [ObservableProperty]
    private string result;
    [ObservableProperty]
    private PackingListDto packingListDto;
    //根据id查询到PalletDto，修改入库日期和库位
    //todo:拍照确认？
    //回传Pallet
    [ObservableProperty]
    private PalletDto palletDto;
    [RelayCommand]
    private async Task GetPalletDtoAsync()
    {
        var id = Result.Split('_').Last();
        PalletDto = await _palletService.GetFirstOrDefaultAsync(Guid.Parse(id))??new PalletDto();
        //如果是空的就将入库日期设置为现在
        PalletDto.ShippingTime ??= DateTime.Now;
    }
    [RelayCommand]
    private async Task GoBackAsync()
    {
        await Shell.Current.GoToAsync("..",
            new Dictionary<string, object?>
            {
                {nameof(PackingListDto),PackingListDto}
            });
        //await Shell.Current.Navigation.PopModalAsync();
    }
    [RelayCommand]
    private async Task ShippingAsync()
    {
        //如果没有入库，则警告用户，必须先入库托盘
        if (PalletDto.WarehousingTime == null)
        {
            await Toast.Make("此托盘还没有入库，请先扫码入库。").Show();
            return;
        }
        await _palletService.UpdateStatusesWithEventAsync(PalletDto.Id.Value, PalletDto);

        await GoBackAsync();
    }

    [RelayCommand]
    private async Task UnShippingAsync()
    {
        //弹窗确认
        var yesNo = await Application.Current!.MainPage!.DisplayAlert("询问", "确定要取消发货吗？", "Yes", "No");
        if (yesNo)
        {
            PalletDto.ShippingTime = null;
            await _palletService.UpdateStatusesWithEventAsync(PalletDto.Id.Value, PalletDto);

            await GoBackAsync();
        }
    }
}